<template>
  <el-drawer
    :visible.sync="drawerVisible"
    :before-close="handleClose"
    :modal="showModal"
    :size="showMobilePage?'100%':'80%'"
    class="todo-drawer-container"
    title="请选择需要关联的审批单">
    <div class="drawer-content">
      <div class="filter">
        <FilterInput
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="approvalFilterList"
          show-search-btn
          line-feed
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus" />
      </div>
      <el-tabs v-model="curTabName" style="margin: 17px 0 8px" @tab-click="onSubActiveOrderChange">
        <el-tab-pane label="全部" name="all"/>
        <el-tab-pane name="selected">
          <span slot="label">已选择<el-badge v-if="selectedData.length" :value="selectedData.length" /></span>
        </el-tab-pane>
      </el-tabs>
      <div class="table-list">
        <div v-loading="listLoading" style="min-height: 100px;">
          <u-table
            v-if="(curTabName === 'all' && list.items.length > 0) || (curTabName === 'selected' && selectedData.length > 0)"
            ref="todoTableRef"
            :data="curTabName === 'all'?list.items:selectedTableData"
            :row-height="49"
            :border="true"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table todo-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            row-class-name="pointer"
            @select="selectTable"
            @select-all="selectTable"
            @row-click="toDetail($event, false)">
            <u-table-column align="center" type="selection" width="50" fixed />
            <template v-for="(settingItem, index) in tableFieldList">
              <u-table-column :key="index" v-bind="rowField[settingItem.field]" >
                <template slot-scope="scope">
                  <template v-if="settingItem.field === 'type'">
                    <p :class="`task-type type${scope.row.type}`">{{ scope.row.type | getTaskType }}</p>
                  </template>
                  <template v-else-if="settingItem.field === 'proposerName'">
                    <div class="column-creator">
                      <img :src="scope.row.avatar || avatarPng" alt="发起人">
                      <!-- <span>{{ scope.row.proposerName }}</span> -->
                      <CheckUserInfo v-if="scope.row.proposerName" :label="scope.row.proposerName" :user-id="scope.row.proposerId" />
                      <div v-else>--</div>
                    </div>
                  </template>
                  <template v-else-if="settingItem.field === 'publicDate'">
                    <div>{{ formatTime(scope.row.createTime) }}</div>
                  </template>
                  <template v-else-if="settingItem.field === 'currentNode'">
                    <ToolTip :content="scope.row.currentNode" />
                  </template>
                  <template v-else-if="settingItem.field === 'approvers'">
                    <ToolTip :content="scope.row.approvers" />
                  </template>
                  <template v-else-if="settingItem.field === 'approverDate'">
                    <div>{{ formatTime(scope.row.approveTime) }}</div>
                  </template>
                  <template v-else-if="settingItem.field === 'status'">
                    <div class="color-status-box">
                      <span v-if="scope.row.status !== null || scope.row.type === 12" :style="{backgroundColor: formatStatus(scope.row, 3).color}" class="dot"/>
                      <p>{{ formatStatus(scope.row, 3).status }}</p>
                    </div>
                  </template>
                  <template v-else-if="settingItem.field === 'abstract'">
                    <template v-if="strJsonParse(scope.row.content) && scope.row.content !== '{}'">
                      <div v-for="(val, name) in strJsonParse(scope.row.content)" :key="name">
                        <el-tooltip placement="top-start">
                          <div slot="content" style="max-width: 300px;">{{ `${name}：${val}` }}</div>
                          <div class="ellipsisOne" style="font-size: 12px">
                            <span style="color: #999">{{ name }}：</span>
                            <span>{{ (val || val === 0) ? val : '--' }}</span>
                          </div>
                        </el-tooltip>
                      </div>
                    </template>
                    <div v-else>--</div>
                  </template>
                </template>
              </u-table-column>
            </template>
          </u-table>
          <EmptyPlaceholder v-else style="padding-bottom: 0" />
        </div>
        <fixed-pagination v-if="curTabName === 'all'" class="bottom-pagination">
          <div class="delete-button-container">
            <el-button :disabled="!hasSelected" size="small" type="primary" class="related-btn" @click="handleSubmit">关联</el-button>
            <el-button size="small" plain type="primary" class="related-btn" @click="handleClose">返回</el-button>
          </div>
          <el-pagination
            v-show="list.items.length > 0"
            :current-page="page"
            :page-size="perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="layout"
            :small="showMobilePage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </fixed-pagination>
        <fixed-pagination v-if="curTabName === 'selected'" class="bottom-pagination">
          <div class="delete-button-container">
            <el-button :disabled="!hasSelected" size="small" type="primary" class="related-btn" @click="handleSubmit">关联</el-button>
            <el-button size="small" plain type="primary" class="related-btn" @click="handleClose">返回</el-button>
          </div>
          <el-pagination
            v-show="selectedData.length > 0"
            :current-page="selectedPage"
            :page-size="selectedPerPage"
            :total="selectedData.length"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="layout"
            :small="showMobilePage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </fixed-pagination>
      </div>
    </div>
  </el-drawer>
</template>
<script>
// api
import { paramsRangeFormat } from '@/utils/paramsFormat';
// mixins
import TableAdaptive from '@/mixins/tableAdaptive';
import tableSelections from '@/mixins/tableSelections';
import Todo from '@/mixins/todo';
import { mapState } from 'vuex';

// 组件
import { rowField } from '@/views/todo/fieldData';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import { getList } from '@/api/todo';
import { strJsonParse } from '@/utils';

export default {
  components: {
    EmptyPlaceholder
  },
  filters: {},
  mixins: [TableAdaptive, tableSelections, Todo],
  props: {
    tableFieldList: {
      type: Array,
      default: () => []
    },
    excludeId: {
      type: String | Number,
      default: ''
    },
    moduleId: {
      type: Number,
      default: -1
    },
    excludeTypes: {
      type: String,
      default: ''
    },
    showModal: { // 是否显示遮罩
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      rowField,
      curTabName: 'all',
      list: {
        items: [],
        total: 0
      },
      idKey: 'id', // 多选框参数
      tableRefName: 'todoTableRef',
      isUmyTable: true,
      page: 1,
      perPage: 20,
      selectedPage: 1,
      selectedPerPage: 20,
      paramsObj: {},
      listLoading: false,
      drawerVisible: false,
      newTabOpen: true,
      selectedData: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    hasSelected() {
      return this.multipleSelectionAll.length;
    },
    selectedTableData() {
      return this.selectedData.slice((this.selectedPage - 1) * this.selectedPerPage, this.selectedPage * this.selectedPerPage);
    },
    approvalFilterList() {
      let filters = JSON.parse(JSON.stringify(this.filterList));
      filters = filters.concat([
        { keyword: 'approver', name: '审批人', labelWidth: '85px', type: 'input' },
        { keyword: 'sender', name: '抄送人', labelWidth: '85px', type: 'input' }
      ]);
      return filters;
    },
    layout() {
      return this.showMobilePage ? 'total, prev, next' : 'total, prev, pager, next, sizes, jumper';
    }
  },
  watch: {
    list: {
      handler: function(data) {
        this.$nextTick(() => {
          if (this.setSelectRow && this.curTabName === 'all') {
            this.setSelectRow(data.items);
          }
        });
      },
      deep: true
    }
  },
  created() {
    // this.fetchData(true);
  },
  methods: {
    strJsonParse,
    openDrawer(list = []) {
      this.fetchData(true);
      this.initData(list);
      this.drawerVisible = true;
    },
    initData(list = []) {
      if (!list || list.length === 0) { return; }
      this.selectedData = list;
      this.multipleSelectionAll = list;
      if (this.setSelectRow && this.curTabName === 'all') {
        this.setSelectRow(this.list.items);
      }
    },
    formatParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      params.page = this.page;
      params.perPage = this.perPage;
      params.onlyUnread = 0;
      params.tabStatus = 2;
      params.includeCC = 1;// 列表数据来源调整为展示当前用户待办中心【我发起的】+【待处理】+【已处理】+【我收到的】所有数据
      params.excludeId = this.excludeId; // 关联审批单排除自身
      params.moduleId = this.moduleId; // 关联审批单所属模块id
      params.notShowIds = this.excludeTypes; // 关联审批单排除类型
      paramsRangeFormat(this.rangeKeyArr, params);
      return params;
    },
    async fetchData(reset = false) {
      this.listLoading = true;
      if (reset) this.page = 1;
      const params = this.formatParams();
      const res = await getList(params);
      this.list = res.data;
      this.listLoading = false;
    },
    handleSubmit() {
      const data = this.selectedData;
      this.$emit('submit', data);
      this.handleClose();
    },
    // 切换列表tab
    onSubActiveOrderChange(data) {
      if (data.paneName === 'all') {
        this.fetchData();
      } else {
        if (this.setSelectRow) this.setSelectRow(this.selectedTableData);
      }
    },
    // 保留数据
    tableSelectionChange(selection) {
      this.selectedData = selection;
      if (this.setSelectRow && this.curTabName === 'selected') this.setSelectRow(this.selectedTableData);
    },
    handleClose() {
      this.drawerVisible = false;
      this.multipleSelectionAll = [];
      this.selectedData = [];
      this.curTabName = 'all';
      this.clearMixinSelection && this.clearMixinSelection();
    },
    queryClick() {
      this.curTabName = 'all';
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    handleSizeChange(val) {
      if (this.curTabName === 'all') {
        this.perPage = val;
        this.fetchData(true);
      } else {
        this.selectedPerPage = val;
        if (this.setSelectRow) this.setSelectRow(this.selectedTableData);
      }
    },
    handleCurrentChange(toPage) {
      if (this.curTabName === 'all') {
        this.page = toPage;
        this.fetchData();
      } else {
        this.selectedPage = toPage;
        if (this.setSelectRow) this.setSelectRow(this.selectedTableData);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/views/todo/todoTable.scss";
.todo-drawer-container {
  & ::v-deep {
    .el-drawer__header {
      height: 48px;
      padding: 0 12px 0 24px;
      margin: 0;
      box-shadow: 2px 4px 5px 0 rgba(221,225,234,0.3);
      display: flex;
      align-items: center;
      > span {
        font-size: 16px;
        color: #333;
      }
      .el-tabs__nav-wrap::after {
        height: 0 !important;
      }
    }
    .el-tabs__header {
      margin: 0;
      border: none;
    }
    .el-drawer__body {
      overflow-y: auto;
      margin-bottom: 56px;
    }
    .el-badge__content{
      background: #FB5227;
    }
    .el-badge__content{
      margin-top: 18px;
    }
    .el-tabs__nav-wrap::after {
      z-index: -1;
    }
    .el-tabs__active-bar {
      bottom: 1px;
    }
    .cell {
      white-space: nowrap !important;
    }
  }
  .drawer-content {
    padding: 22px 24px 0;
    overflow-y: auto;
    .table-list {
      border-radius: 10px;
      .el-row {
        padding: 0;
      }
      .delete-button-container {
        flex:1;
        height: 32px;
        display: flex;
        align-items: center;
        .related-btn {
          margin-left: 20px;
          padding-left: 12px;
          padding-right: 12px;
        }
      }
      ::v-deep .pagination-flex {
        position: absolute;
        width: 100% !important;
      }
    }
  }
}
</style>
